import type { Todo, HistoryRecord } from "@/types"
import { StorageService } from "./storage"

export class HistoryService {
  private static instance: HistoryService
  private storage: StorageService

  constructor() {
    this.storage = StorageService.getInstance()
  }

  static getInstance(): HistoryService {
    if (!HistoryService.instance) {
      HistoryService.instance = new HistoryService()
    }
    return HistoryService.instance
  }

  updateDailyHistory(todos: Todo[]): void {
    const today = new Date().toISOString().split("T")[0]
    const history = this.storage.loadHistory()

    // Find or create today's record
    let todayRecord = history.find((record) => record.date === today)

    const createdToday = todos.filter((todo) => {
      const createdDate = todo.createdAt.toISOString().split("T")[0]
      return createdDate === today
    })

    const completedToday = todos.filter((todo) => {
      if (!todo.completedAt) return false
      const completedDate = todo.completedAt.toISOString().split("T")[0]
      return completedDate === today
    })

    const totalTasks = todos.length
    const completedTasks = todos.filter((todo) => todo.completed).length
    const completionRate = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0

    if (todayRecord) {
      // Update existing record
      todayRecord.createdTasks = createdToday
      todayRecord.completedTasks = completedToday
      todayRecord.totalTasks = totalTasks
      todayRecord.completionRate = completionRate
    } else {
      // Create new record
      todayRecord = {
        id: `history-${today}`,
        date: today,
        createdTasks: createdToday,
        completedTasks: completedToday,
        totalTasks,
        completionRate,
      }
      history.push(todayRecord)
    }

    // Sort by date (newest first) and keep only last 30 days
    const sortedHistory = history.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()).slice(0, 30)

    this.storage.saveHistory(sortedHistory)
  }

  getHistory(): HistoryRecord[] {
    return this.storage.loadHistory()
  }

  getTodayRecord(): HistoryRecord | null {
    const today = new Date().toISOString().split("T")[0]
    const history = this.getHistory()
    return history.find((record) => record.date === today) || null
  }
}
